package com.ray.ba.code.generator.app.service.impl;

import cn.hutool.db.Entity;
import com.ray.ba.code.generator.app.service.CodeGeneratorService;
import com.ray.ba.starter.code.generator.CodeGenerator;
import com.ray.ba.starter.code.generator.TemplateResourceEnum;
import com.ray.ba.starter.code.generator.entity.GenConfig;
import com.ray.ba.starter.code.generator.util.DbUtil;
import com.ray.ba.starter.web.api.ResponsePage;
import com.ray.ba.starter.web.exception.BaseException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * CodeGeneratorServiceImpl
 *
 * @author ray
 * @date 2020/5/7
 */
@Service
@AllArgsConstructor
public class CodeGeneratorServiceImpl implements CodeGeneratorService {

    @Override
    public ResponsePage<Entity> queryTableByTableNameLike(DataSource dataSource, String tableName, Integer pageNum, Integer pageSize) {
        try {
            List<Entity> tables;
            if (StringUtils.isEmpty(tableName)) {
                tables = DbUtil.listTable(dataSource, pageNum, pageSize);
            } else {
                tables = DbUtil.queryTableByTableNameLike(dataSource, tableName, pageNum, pageSize);
            }
            BigDecimal count = DbUtil.countTableByTableNameLike(dataSource, tableName);
            return ResponsePage.getInstance(pageNum, pageSize, count.longValue(), tables);
        } catch (SQLException e) {
            throw new BaseException(String.format("can not query tables by table name like %s", tableName));
        }
    }

    @Override
    public byte[] generatorCode(DataSource dataSource, GenConfig genConfig) {
        List<TemplateResourceEnum> templateResourceList = Arrays.asList(TemplateResourceEnum.values());
        CodeGenerator codeGenerator = CodeGenerator.builder().dataSource(dataSource).genConfig(genConfig).templateResourceList(templateResourceList).build();
        return codeGenerator.generate().getZipContent();
    }
}
